const createAlbum = document.getElementById("createAlbum");
const uploadImg = document.getElementById("uploadImg");
const selectFile = document.getElementById("selectFile");
const createAlbumModal = document.getElementById("createAlbumModal");
const submitAlbumBtn = document.getElementById("submitAlbumBtn");
const menu = document.querySelector(".menu");
const imgList = document.querySelector(".imgList");

let curAlbum = '默认';    //记录当前在那个相册

//获取相册
function getAlbum(){
  // const imgList = document.querySelector(".imgList");
  // removAll(imgList, 'li');
  fetch("/album/list", {
    method: "GET"
  }).then(function(response){
    return response.json();
    // return response.text();
  }).then(function(res){
    // console.log(res);
    if(res.status == 0){
      removAll(menu, 'li');
      res.list.forEach(function(name, i){
        // console.log(name);
        let li = document.createElement('li');
        let item = document.createElement('a');
        let close = document.createElement('a');
        (name == curAlbum) && (li.setAttribute("class", "active"));
        item.setAttribute('data-url', '/image/list');
        item.setAttribute('class', 'item');
        item.innerHTML = name;
        close.setAttribute('data-url', '/album/delete');
        close.setAttribute('data-name', name);
        close.setAttribute('class', 'close');
        close.innerHTML = 'x';
        close.addEventListener("click", delAlbum);
        li.appendChild(item);
        if(name !== '默认' && name !== '全部'){
          li.appendChild(close);
        }
        menu.appendChild(li);
      })
      getImgByAlbumName('/image/list', curAlbum);
    }else {
      alert("位置错误");
    }
  })
}
getAlbum();

//清空某元素下的所有子元素
function removAll(parent, childTag){
  let childList;
  while((childList = parent.getElementsByTagName(childTag)).length > 0){
    parent.removeChild(parent.querySelector(childTag));
  }
}


//打开创建相册模态框
createAlbum.addEventListener("click", function(){
  createAlbumModal.getElementsByTagName('input')[0].value = '';
  createAlbumModal.removeAttribute('class');
})

//创建相册
submitAlbumBtn.addEventListener("click", function(){
  let name = document.querySelector("#createAlbumModal input").value;
  if(!name){
    alert("相册名不能为空");
    return;
  }
  fetch("/album/create", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({name: name})
  }).then(function(response){
    return response.json();
    // return response.text();
  }).then(function(res){
    // console.log(res);
    if(res.status == 0){
      getAlbum();
      createAlbumModal.setAttribute('class', 'hide');
    }else {
      alert("该相册已存在");
    }
  })
})

//取消创建相册
createAlbumModal.querySelector(".close").onclick = function(){
  createAlbumModal.setAttribute('class', 'hide');
}

//删除相册
function delAlbum(){
  let that = this;
  if(confirm("确认要删除？")){
    fetch(that.getAttribute("data-url"), {
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({name: that.getAttribute('data-name')})
    }).then(function(res){
      return res.json();
    }).then(function(res){
      if(res.status == 0){
        getAlbum();
      }else {
        alert("删除失败");
      }
    })
  }
}
// //删除相册
// menu.onclick = function(event){
//   var event = event || window.event;
//   var target = event.target || event.srcElement;
//   if(target.nodeName.toLowerCase() === 'a' && target.className == 'close'){
//     console.log(target, target.nodeName, target.nodeName.toLowerCase());
//
//   }
// }

//切换相册
menu.onclick = function(event){
  var event = event || window.event;
  var target = event.target || event.srcElement;
  if(target.nodeName.toLowerCase() === 'a' && target.className == 'item'){
    // console.log(target, target.getAttribute('data-url'), target.innerHTML);
    curAlbum = target.innerHTML;
    // console.log(curAlbum);
    getImgByAlbumName(target.getAttribute('data-url'), curAlbum);
    menu.querySelectorAll('li').forEach(function(item, i){
      // console.log(item);
      item.removeAttribute('class');
    })
    target.parentNode.setAttribute('class', 'active');
  }
}

//获取某个相册中的图片
function getImgByAlbumName(url, name){
  // console.log(url, name);
  fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({album: curAlbum, name: name})
  }).then(function(response){
    return response.json();
  }).then(function(response){
    // console.log('图片', response);
    if(response.status == 0){
      removAll(imgList, 'li');
      response.list.forEach(function(image, i){
        let li = document.createElement('li');
        let img = document.createElement('img');
        let a = document.createElement('a');
        img.setAttribute('src', '/image/read/' +curAlbum + '/' + image);
        // console.log('/image/read/' +curAlbum + '/' + image);
        a.innerHTML = 'x';
        a.setAttribute('class', 'close');
        a.setAttribute('data-image-url', image.replace('\\image\\read\\', ''));
        a.setAttribute('data-album-name', name);
        li.appendChild(img);
        li.appendChild(a);
        imgList.appendChild(li);
      })
    }else {
      alert("获取" + name + "相册中的图片失败");
    }
  })
}


//删除图片
imgList.onclick = function(event){
  var event = event || window.event;
  var target = event.target || event.srcElement;
  if(target.nodeName.toLowerCase() === 'a' && target.className == 'close'){
    // console.log(target.getAttribute('data-image-url'));
    if(confirm("确认要删除？")){
      fetch('/image/delete', {
        method: 'POST',
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({album: target.getAttribute('data-album-name'), name: target.getAttribute('data-image-url')})
      }).then(function(res){
        return res.json();
      }).then(function(res){
        if(res.status == 0){
          getImgByAlbumName('/image/list', target.getAttribute('data-album-name'));
        }else if(res.status == -2){
          alert(res.message);
        } else{
          alert("删除失败");
        }
      })
    }

  }
}

//选择图片
uploadImg.onclick = function(){
  var button = document.createEvent("MouseEvents");
  button.initEvent("click", true, true)
  // console.log(11111111111)
  selectFile.dispatchEvent(button);
}

//上传图片
function uploadImage(){
  let input = event.target;
  let formData = new FormData();
  formData.append('myfile', input.files[0]);
  formData.append('album', curAlbum)   //相册名字
  console.log(curAlbum)
  fetch('/image/upload', {
    method: 'POST',
    // headers: {
    //   "Content-Type": "multipart/form-data"
    // },
    body: formData
  }).then(function(res){
    return res.json();
  }).then(function(res){
    if(res.status == 0){
      getImgByAlbumName('/image/list', curAlbum);
    }else if(res.status == -2){

    } else{

    }
  })


  // let reader = new FileReader();
  // reader.onload = function(){
  //   let formData = new FormData();
  //   formData.append('myfile', reader.result);
  //   formData.append('album', curAlbum)
  //   console.log(curAlbum)
  //   fetch('/image/upload', {
  //     method: 'POST',
  //     headers: {
  //       "Content-Type": "multipart/form-data"
  //     },
  //     body: formData
  //   }).then(function(res){
  //     return res.json();
  //   }).then(function(res){
  //     if(res.status == 0){
  //
  //     }else if(res.status == -2){
  //
  //     } else{
  //
  //     }
  //   })
  // }
  // reader.readAsDataURL(input.files[0]);
}
